package com.doupi.partner.util;

import com.alibaba.fastjson.JSON;
import com.doupi.partner.util.constant.UtilConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * API公共异常类
 * 
 * @author Super Jens Wang
 *
 * @version 1.0 @ 2016年7月20日 上午4:47:54
 */
public class RuntimeBusinessException extends RuntimeException {

	private static final long serialVersionUID = -1376645320861107365L;
	private static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8";

	private static final String OTHER_ERROR_MESSAGE = "系统异常，请联系管理员";

	private String code;

	private RuntimeBusinessException(String code, String message) {
		super(message);
		this.code = code;
	}

	/**
	 * 创建异常
	 * 
	 * @param code
	 *            异常code
	 * @param message
	 *            异常消息
	 * @return 异常实例
	 */
	public static RuntimeBusinessException createException(String code, String message) {
		return new RuntimeBusinessException(code, message);
	}

	/**
	 * 创建异常
	 * 
	 * @param message
	 *            异常消息
	 * @return 异常实例
	 */
	public static RuntimeBusinessException createException(String message) {
		return createException(UtilConstants.FAIL_STATUS_CODE, message);
	}

	/**
	 * 异常的code
	 */
	public String getCode() {
		return code;
	}

	/**
	 * 统一系统异常处理
	 * 
	 * @param httpRequest
	 *            http request
	 * @param httpResponse
	 *            http response
	 * @param handler
	 *            异常处理
	 * @param ex
	 *            异常信息
	 * @param logger
	 *            日志
	 */
	public static void handlerSystemException(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Object handler, Exception ex, Logger logger) {
		Map<String, Object> errorMsg = new HashMap<>();
		errorMsg.put("请求IP", HttpRequestUtils.getClientIp(httpRequest));
		errorMsg.put("请求refer", HttpRequestUtils.getReferUrl(httpRequest));
		errorMsg.put("请求URL", httpRequest.getRequestURL().toString());
		errorMsg.put("请求参数", httpRequest.getParameterMap().toString());
		errorMsg.put("请求参数JSON", httpRequest.getParameterMap());
		errorMsg.put("theExecutedHandler", handler.toString());
		errorMsg.put("theExecutedHandlerJSON", handler);
		Marker marker = MarkerFactory.getMarker("email");

		logger.error(marker, JSON.toJSONString(errorMsg), ex);

		try {
			if (HttpRequestUtils.isAjax(httpRequest)) {
				httpResponse.setContentType(JSON_CONTENT_TYPE);
				AjaxResponse ajaxResponse = new AjaxResponse(UtilConstants.FAIL_STATUS_CODE, StringUtils.EMPTY);
				if (ex instanceof RuntimeBusinessException) {
					ajaxResponse.setMessage(ex.getMessage());
				} else {
					ajaxResponse.setMessage(OTHER_ERROR_MESSAGE);
				}
				httpResponse.getWriter().println(JSON.toJSONString(ajaxResponse));
				httpResponse.flushBuffer();
			}
		} catch (Exception e) {
			logger.error("处理异常", e);
		}
	}
}
